//
//  firstViewConrtoller.m
//  project-A (pianke)
//
//  Created by dllo on 16/1/24.
//  Copyright © 2016年 scott. All rights reserved.
//

#import "firstViewConrtoller.h"
#import "NightManager.h"
#import "AccountManager.h"
#import "leftViewController.h"
#import "CellOne.h"
#import "CellTwo.h"
#import "CellThree.h"
#import "WebviewControl.h"
#import "CelloneTab.h"
#import "Model2.h"
#import "videoController.h"
#import "ModelOfTravl.h"
#import "InfoViewController.h"
#import "VCtravles.h"
#import "AppDelegate.h"
#import <DKNightVersion.h>
#import "webOfdic.h"


#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height




@interface firstViewConrtoller ()<UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,Celldelegate,TravlDelelgate>

@property (nonatomic,retain)UIButton *mainButton;

@property (nonatomic,retain)UIButton *exchangeButton;
@property (nonatomic,retain)UICollectionView *collection;
@property (nonatomic,retain)UIView *viewOForredline;
//按钮

@property (nonatomic,retain)UIButton *button1;

@property (nonatomic,retain)UIButton *button2;

@property (nonatomic,retain)UIButton *button3;

@property (nonatomic,retain)NSString *urlstring;

@property (nonatomic,retain)NSString *ScreenshotsPickPath;

@end

@implementation firstViewConrtoller

static int ScreenshotIndex=0;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"首页";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBarHidden = NO;
     self.edgesForExtendedLayout = UIRectEdgeNone;
    
       //创建scrollview
    
    self.navigationController.navigationBar.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor],  [UIColor colorWithRed:0.16 green:0.14 blue:0.13 alpha:1]);
    
    self.navigationController.navigationBar.dk_tintColorPicker = DKColorWithColors([UIColor whiteColor],  [UIColor colorWithRed:0.64 green:0.74 blue:0.86 alpha:1]);
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorWithColors([UIColor colorWithRed:0 green:0.8 blue:0.86 alpha:1],[UIColor colorWithRed:0.16 green:0.14 blue:0.13 alpha:1]);
    
   
   
    
    
    
    
    [self creatRedline];
    [self creatCollection];
    
    [self creatKVOAction];
    
    [self changeNaviionItem];
    
    [self creatbutton];

}
-(void)dealloc{
    [_ScreenshotsPickPath release];
    [_collection release];
    [_viewOForredline release];
    [_exchangeButton release];
    [_mainButton release];
    [_button1 release];
    [_button2 release];
    [_button3 release];
    [_urlstring release];
    [super dealloc];
    
}

#pragma mark 创建按钮

-(void)creatbutton{
    self.button1 = [[UIButton alloc]init];
    self.button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button1.frame = CGRectMake(0, 0, WIDTH/3.0f,40);
    [self.button1 setTitle:@"美文" forState:UIControlStateNormal];
    [self.button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.button1.backgroundColor = [UIColor whiteColor];
    [self.button1 addTarget:self action:@selector(jingxuanbutton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.button1];
    self.button1.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:0.16 green:0.14 blue:0.13 alpha:1]);
    
    
    
    [self.button1 release];
    
    
    self.button2 = [[UIButton alloc]init];
    self.button2 = [UIButton buttonWithType:UIButtonTypeCustom];
   
    self.button2.backgroundColor = [UIColor whiteColor];
    self.button2.frame = CGRectMake(WIDTH / 3.0f,0 , WIDTH/3.0f,40);
     [self.button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.button2 setTitle:@"游记" forState:UIControlStateNormal];
    [self.button2 addTarget:self action:@selector(zhuantaibutton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.button2];
    self.button2.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:0.16 green:0.14 blue:0.13 alpha:1]);
    
    
    [self.button2 release];
    
    
    self.button3 = [[UIButton alloc]init];
    self.button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button3.backgroundColor = [UIColor whiteColor];
    self.button3.frame = CGRectMake(WIDTH / 3.0f * 2, 0, WIDTH/3.0f,40);
    [self.button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.button3 setTitle:@"游戏" forState:UIControlStateNormal];
    [self.button3 addTarget:self action:@selector(suipianbutton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.button3];
    self.button3.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:0.16 green:0.14 blue:0.13 alpha:1]);
    [self.button3 release];
}

#pragma mark 按钮动作

-(void)jingxuanbutton:(UIButton *)button{
    
     [self.collection setContentOffset:CGPointMake(0, 0) animated:YES];
        
      }

-(void)zhuantaibutton:(UIButton *)button{
    
    [self.collection setContentOffset:CGPointMake(WIDTH, 0) animated:YES];
    

}

-(void)suipianbutton:(UIButton *)button{
    [self.collection setContentOffset:CGPointMake(WIDTH * 2, 0) animated:YES];
    
}



#pragma mark 创造collection
-(void)creatRedline{
    self.viewOForredline = [[UIView alloc]initWithFrame:CGRectMake(0, 40, WIDTH/3.0f, 2)];
    self.viewOForredline.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:self.viewOForredline];
    
    [self.viewOForredline release];
}
-(void)creatCollection{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - 42);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
   
    
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 42, WIDTH, HEIGHT - 42) collectionViewLayout:flowLayout];
    [self.view addSubview:self.collection];
    self.collection.dataSource = self;
    self.collection.delegate = self;
    self.collection.backgroundColor = [UIColor whiteColor];
    self.collection.pagingEnabled = YES;
    self.collection.bounces = NO;
    [self.collection registerClass:[CellOne class] forCellWithReuseIdentifier:@"pool1"];
    [self.collection registerClass:[CellTwo class] forCellWithReuseIdentifier:@"pool2"];
    [self.collection registerClass:[CellThree class] forCellWithReuseIdentifier:@"pool3"];
    
    
     [flowLayout release];
    [self.collection release];
}

#pragma mark - Collection Delegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return 3;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        CellOne *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool1" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor lightGrayColor];
        
        cell.layer.borderWidth = 2;
        cell.layer.borderColor = [UIColor lightGrayColor].CGColor;
        
        cell.layer.masksToBounds = YES;
        
        
        [cell posturl];
        
        return cell;
    }else if (indexPath.row == 1){
        CellTwo *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool2" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor lightGrayColor];
        [cell geturlasd];
        cell.delegate = self;
        return cell;
       
    }else{
        CellThree *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool3" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor lightGrayColor];
        
        [cell geturl];
        cell.delegate = self;
        
        return cell;
    }
    
}

#pragma mark 协议方法
-(void)didClickWith:(Model2 *)model{
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"array.plist"];
    
    NSMutableArray *arr =  [NSMutableArray arrayWithContentsOfFile:file];
    
    NSLog(@"%ld",arr.count);
    
    self.count = 0;
    for (webOfdic *dic in arr) {
        
        if ([[dic objectForKey:@"title"] isEqualToString:model.title]) {
            
            self.count += 1;
            NSLog(@"%ld",self.count);
        }else{
            
            self.count += 0;
            
            
            NSLog(@"%ld",self.count);
            
        }
    }

    
    if ([model.video_url isEqualToString:@""]) {
        NSLog(@"%@",model.idd);
        WebviewControl *web = [[WebviewControl alloc]init];
        
              NSString *str = [NSString stringWithFormat:@"http://lol.zhangyoubao.com/mobiles/item/%@?v_=400609&size=middle&t=1453899180",model.idd];
            web.urlstring = str;
    
        web.count = self.count;
        
        web.titlea = model.title;
        web.desc = model.desc;
        web.video_url = model.video_url;
        web.published = model.published;
        
        web.weight_new = model.weight_new;
        web.idd = model.idd;
        web.pic_url = model.pic_url;

        
        [self.navigationController pushViewController:web animated:YES];
        
        [web release];

    }else{
       
         WebviewControl *web = [[WebviewControl alloc]init];
    
            web.count = self.count;
            web.titlea = model.title;
            web.desc = model.desc;
            web.video_url = model.video_url;
            web.published = model.published;
            
            web.weight_new = model.weight_new;
            web.idd = model.idd;
            web.pic_url = model.pic_url;
    

        NSString *str = model.video_url;
        web.urlstring = str;
        
       
        [self.navigationController pushViewController:web animated:YES];
        
        
        [web release];

    }
    }


#pragma mark  协议方法1

-(void)didSeletedWith:(ModelOfTravl *)model{
    
   InfoViewController  *info = [[InfoViewController alloc]init];
    
 
    NSString *strid = [NSString stringWithFormat:@"%@",[model.user objectForKey:@"id"]];
    
    NSString *str = [NSString stringWithFormat:@"http://chanyouji.com/api/users/%@.json?page=1",strid];
    
    info.idstring = str;
    
    
    
    NSString *strid2 = [NSString stringWithFormat:@"%@",[model.user objectForKey:@"id"]];
    
    NSString *str2 = [NSString stringWithFormat:@"http://chanyouji.com/api/users/likes/%@.json?per_page=15&page=1",strid2];
    
    info.idstring2 = str2;
    
        
    [self.navigationController pushViewController:info animated:YES];
//    [info autorelease];
    
}


-(void)didSeletedTripWith:(ModelOfTravl *)model{
    NSLog(@"旅游行程界面");
    VCtravles *travel = [[VCtravles alloc]init];
    NSString *strid = [NSString stringWithFormat:@"%@",model.idd];
    NSString *str = [NSString stringWithFormat:@"http://chanyouji.com/api/trips/%@.json",strid];
    NSLog(@"%@",str);
    travel.strURl = str;
        [self.navigationController pushViewController:travel animated:YES];
//    [travel release];
    
}





-(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
-(void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(nonnull NSIndexPath *)sourceIndexPath toIndexPath:(nonnull NSIndexPath *)destinationIndexPath{
    
    
    
}

#pragma mark  KVO(键值对观察者)
-(void)creatKVOAction{
    [self.collection addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:@"ddd"];
 }

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    CGFloat x = [[change objectForKey:@"new"]CGPointValue].x;
    CGFloat redX = x * WIDTH / 3 / WIDTH;
    
    self.viewOForredline.transform = CGAffineTransformMakeTranslation(redX, 0);
}
#pragma mark 按键

-(void)changeNaviionItem{
    //中间的是消息和通话
    UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:@[@"消息",@"通话"]];
    self.navigationItem.titleView = segment;
    segment.selectedSegmentIndex = 0;
    //右边的是搜索
    
    UIBarButtonItem *item3 = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"jieping2"] style:UIBarButtonItemStylePlain target:self action:@selector(actionModel:)];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"sou"] style:UIBarButtonItemStylePlain target:self action:@selector(searchAction:)];
    self.navigationItem.rightBarButtonItems = @[item2,item3];
    
    
    //左边的按键
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"gd"] style:UIBarButtonItemStylePlain target:self action:@selector(action:)];
    self.navigationItem.leftBarButtonItem = item;
    
    [item3 release];
    [item2 release];
    [item release];
}

#pragma mark 搜索动作
-(void)searchAction:(UIButton *)button{
    
    WebviewControl *web = [[WebviewControl alloc]init];
   
    
    NSString *string = @"http://www.baidu.com";
    
    
    web.urlstring = string;
    
    [self.navigationController pushViewController:web animated:YES];
    
    [web release];
}

#pragma mark 抽屉页面
-(void)action:(UIButton *)button{
    
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if (tempAppDelegate.LeftSlideVC.closed)
    {
        [tempAppDelegate.LeftSlideVC openLeftView];
    }
    else
    {
        [tempAppDelegate.LeftSlideVC closeLeftView];
    }

    
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    NSLog(@"viewWillDisappear");
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC setPanEnabled:NO];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"viewWillAppear");
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC setPanEnabled:YES];
}


#pragma mark 夜间模式
-(void)actionModel:(UIButton *)button{
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(1242,2205), YES, 0);     //设置截屏大小
    [[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef imageRef = viewImage.CGImage;
    
    CGRect rect = CGRectMake(0, 0, 1242,2205);//这里可以设置想要截图的区域
    CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
    UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];
    UIImageWriteToSavedPhotosAlbum(sendImage, nil, nil, nil);//保存图片到照片库
    NSData *imageViewData = UIImagePNGRepresentation(sendImage);
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pictureName= [NSString stringWithFormat:@"screenShow_%d.png",ScreenshotIndex];
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:pictureName];
    NSLog(@"截屏路径打印: %@", savedImagePath);
    //这里我将路径设置为一个全局String，这里做的不好，我自己是为了用而已，希望大家别这么写
    [self SetPickPath:savedImagePath];
    
    [imageViewData writeToFile:savedImagePath atomically:YES];//保存照片到沙盒目录
    CGImageRelease(imageRefRect);
    ScreenshotIndex++;

 
}
- (void)SetPickPath:(NSString *)PickImage {
    _ScreenshotsPickPath = PickImage;
}
//获取路径<这里我就直接用于邮件推送的代码中去了，能达到效果，但肯定有更好的写法>
- (NSString *)GetPickPath {
    return _ScreenshotsPickPath;
}


-(void)setNightModel{
//    [NightManager setLabelColorWithLabel:self.label];
    
    [NightManager setBackgroundColorWithView:self.view];
    [NightManager setBackgroundColorWithView:self.collection];
    [NightManager setButtonTitleColorWithButton:self.mainButton];
    [NightManager setButtonTitleColorWithButton:self.exchangeButton];
    
}

-(void)setLightDayModel{
//     [NightManager setLabelColorWithLabel:self.label];
    [NightManager setBackgroundColorWithView:self.view];
    [NightManager setBackgroundColorWithView:self.collection];
    [NightManager setButtonTitleColorWithButton:self.mainButton];
    [NightManager setButtonTitleColorWithButton:self.exchangeButton];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
